<template>
  <a-modal :width="1200" v-model:visible="showAddNegativeKeyword" title="新增否定关键词" title-align="start" :mask-closable="false" :on-before-ok="submitData" :ok-loading="submitLoading" @cancel="closedDialog">
    <a-form ref="formRef" :model="formInfo" :rules="rules">
      <a-row>
        <a-col :span="8">
          <a-form-item field="shopId" label="店铺：" label-col-flex="80px">
            <a-select v-model="formInfo.shopId" placeholder="请选择" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search @change="changeShop">
              <a-option v-for="(shopInfo, i) in shopList" :key="i" :value="shopInfo.id" :label="shopInfo.shopName" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="广告组合：" label-col-flex="100px">
            <a-select v-model="formInfo.portfolioId" placeholder="请选择" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search @change="changePortfolio" @search="getPortfolioList" :filter-option="false">
              <a-option v-for="(portfolio, i) in portfolioList" :key="i" :value="portfolio.portfolioId" :label="portfolio.portfolioName" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="campaignId" label="广告活动：" label-col-flex="100px">
            <a-select v-model="formInfo.campaignId" placeholder="请选择" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search @change="changeCampaign" @search="getCampaignList" :filter-option="false">
              <a-option v-for="(campaign, i) in campaignList" :key="i" :value="campaign.campaignId" :label="campaign.campaignName" />
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item field="adGroupId" label="广告组：" label-col-flex="100px">
            <a-select v-model="formInfo.adGroupId" placeholder="请选择" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search @search="getAdGroupList" :filter-option="false">
              <a-option v-for="(adGroup, i) in adGroupList" :key="i" :value="adGroup.adGroupId" :label="adGroup.adGroupName" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="活动类型：" label-col-flex="100px">
            <p>{{ AdTypes[adType] || '--' }}</p>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 否定关键词 -->
    <CreateSpNegKeyword :defaultVal="defaultVal" height="300px" ref="negKeywordRef" />
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { createNegativeKeyword, getAllPortfoliosList, getAllCampaignList, getAllAdGroupList } from '@/api/advert'
  import CreateSpNegKeyword from '../createSpNegKeyword.vue'
  import useAdvertStore from '@/store/modules/advert'
  import useBaseDataStore from '@/store/modules/base-data'
  import { AdTypes } from '../../../types'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    defaultVal: {
      type: String,
    },
    level: {
      type: String,
    },
    type: {
      type: String,
      default: 'add', //add添加当前，addOther添加到其他否定
    },
    info: {
      type: Object,
      default: () => {},
    },
  })
  onMounted(() => {
    getShopList()
    // 添加否定关键词的时候，需要根据关键词的层级显示默认的活动信息
    if (props.type == 'add' && props.level) {
      setFormInfo()
    } else {
      resetListOptions()
    }
  })

  const showAddNegativeKeyword = ref(props.isShow)
  const submitLoading = ref(false)
  const negKeywordRef = ref()
  const formInfo = ref<any>({})
  const formRef = ref()
  const advertStore = useAdvertStore()
  const adGroupList = ref<Array<any>>([])
  const portfolioList = ref<Array<any>>([])
  const campaignList = ref<Array<any>>([])
  const shopList = ref<Array<any>>([])
  const useBaseData = useBaseDataStore()

  const rules = ref({
    shopId: [{ required: true, message: '请选择店铺' }],
    adGroupId: [{ required: true, message: '请选择广告组' }],
    campaignId: [{ required: true, message: '请选择广告活动' }],
    portfolioId: [{ required: true, message: '请选择广告组合' }],
  })

  const adType = computed(() => {
    return campaignList.value.find((el: any) => el.campaignId === formInfo.value.campaignId)?.adType
  })
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    shopList.value = useBaseData.shopList
  }

  // 添加否定关键词的时候，需要根据关键词的层级显示默认的活动信息
  function setFormInfo() {
    formInfo.value.shopId = props.info.shopId
    formInfo.value.campaignId = props.info?.campaignId
    if (props.level == 'adGroup') {
      // 广告组详情
      formInfo.value.adGroupId = props.info?.adGroupId
    }
    getPortfolioList()
    getCampaignList(props.info?.campaignName)
    getAdGroupList(props.info?.adGroupName)
  }
  // 重新查询所有选项
  function resetListOptions() {
    getPortfolioList()
    getCampaignList()
    getAdGroupList()
  }
  // 切换店铺
  function changeShop() {
    formInfo.value.portfolioId = null
    formInfo.value.campaignId = null
    formInfo.value.adGroupId = null
    resetListOptions()
  }
  // 切换广告组合
  function changePortfolio() {
    formInfo.value.campaignId = null
    formInfo.value.adGroupId = null
    getCampaignList()
    getAdGroupList()
  }
  // 切换广告活动
  function changeCampaign() {
    formInfo.value.adGroupId = null
    getAdGroupList()
  }
  // 关闭
  function closedDialog() {
    showAddNegativeKeyword.value = false
    emit('closed')
  }
  // 获取广告组合列表
  async function getPortfolioList(val?: string) {
    const res: any = await getAllPortfoliosList({
      search: val,
      shopId: formInfo.value.shopId,
    })
    portfolioList.value = res?.data || []
  }
  // 获取广告活动列表
  async function getCampaignList(val?: string) {
    const res: any = await getAllCampaignList({
      search: val,
      shopId: formInfo.value.shopId,
      portfolioId: formInfo.value.portfolioId,
    })
    campaignList.value = res?.data || []
  }

  // 获取广告组列表
  async function getAdGroupList(val?: string) {
    const res: any = await getAllAdGroupList({
      search: val,
      shopId: formInfo.value.shopId,
      portfolioId: formInfo.value.portfolioId,
      campaignId: formInfo.value.campaignId,
    })
    adGroupList.value = res?.data || []
  }
  // 创建关键词
  async function submitData() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false

    let negativeKeywordInfos = negKeywordRef.value.setCreateData()?.negativeKeywordInfos || []
    if (!negativeKeywordInfos.length) {
      Message.error('关键词不能为空')
      return false
    }
    let params = {
      adType: adType.value,
      shopId: formInfo.value.shopId,
      adGroupId: formInfo.value.adGroupId,
      campaignId: formInfo.value.campaignId,
      negativeKeywordInfos: negativeKeywordInfos?.map((el: any) => {
        return {
          keywordText: el.negativeKeyword,
          matchType: el.negativeKeywordMatchType,
        }
      }),
    }
    const res: any = await createNegativeKeyword(params)
    if (!res) return false
    Message.success('添加成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped></style>
